#!/usr/bin/python
import zipfile, os, pickle, sys

archivename = sys.argv[1] #'MathJax-v1.0.1a.zip'
#print archivename
#sys.exit(0)
zf = zipfile.ZipFile(archivename)
fl = zf.infolist()

compressed_size = sum([fl[i].compress_size for i in range(len(fl))])
uncompressed_size = sum([fl[i].file_size for i in range(len(fl))])

max_file_size = 10485760 # max appengine filesize in byte

size_of_archive = os.path.getsize(archivename)
number_of_archives = int(size_of_archive/max_file_size*1.0)+1+4 # four archives more than is needed, just to be sure..

size_of_small_archive = int(1.0*compressed_size / number_of_archives) + 1

print compressed_size, number_of_archives, 1.0*compressed_size / number_of_archives, size_of_small_archive
#sys.exit(0)

new_archive_names = ["%s.%i" % (archivename,i) for i in range(number_of_archives)]

filename_mapping = {}
asize = 0
#afl = []
counter = 0
sza = zipfile.ZipFile(new_archive_names[counter],'w') #small zip archive

#directory = os.path.abspath(os.path.dirname(sys.argv[0]))
for finfo in fl:
  asize += finfo.compress_size
  if asize > size_of_small_archive:
    sza.close() # close archive
    asize = 0
    #afl = []
    counter += 1
    # open new-archive:
    sza = zipfile.ZipFile(new_archive_names[counter],'w') #small zip archive
  #afl.append(finfo.filename)
  filename_mapping[(archivename,finfo.filename)] = (new_archive_names[counter], finfo.filename)
  opened = zf.open(finfo.filename) # open filename
  data = opened.read() # read data
  opened.close() # close
  sza.writestr(finfo.filename, data) # write to small archive
  print (archivename,finfo.filename)
  print (new_archive_names[counter], finfo.filename)


# write pickled filename_mapping .pkl file:
fm = open('%s.pkl' % archivename,'w')
pickle.dump(filename_mapping,fm)
fm.close()

print new_archive_names
